<template>
<div>
  <Button type="primary" @click=" onOpen">添加</Button> 
 <Button type="error" @click="onDeletes">删除多条记录</Button>
    <Input v-model="filter.name" @on-enter="onSearch">
            <Button slot="append" icon="ios-search" @click="onSearch"></Button>
               
        </Input>

  <Table border :columns="columns" :data="filter.list" @on-selection-change="onSelectionChange"></Table>
   <Page :total="filter.total" size="small"  
        show-total show-elevator show-sizer
        @on-change="onChange"
        @on-page-size-change="onPageSizeChange"></Page>


          <Modal
            v-model="modal"
            title="数据操作"
        >
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">                
                <FormItem label="用户名" prop="name">
                    <Input v-model="formValidate.name" placeholder="请输入姓名"></Input>
                </FormItem>
                <FormItem label="密码" prop="password">
                    <Input v-model="formValidate.password" placeholder="请输入密码"></Input>
                </FormItem>
                 <FormItem label="手机号" prop="phone">
                    <Input v-model="formValidate.phone" placeholder="请输入手机号"></Input>
                </FormItem>
                <FormItem label="邮箱" prop="email">
                    <Input v-model="formValidate.email" placeholder="请输入邮箱"></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                    <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
        </Modal>
</div>
</template>
<script>
import md5 from 'crypto-js/md5'
    export default {
        data () {
            //邮箱验证
            const validateEmail = (rule, value, callback) => {
           
                // 模拟异步验证效果

                var reg=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/ 
                setTimeout(() => {
                    if (!reg.test(value)) {
                        callback(new Error('请输入正确的邮箱'));
                    } else {
                         callback();
                    }
                }, 1000);
            };

            //手机号验证
            const validatePhone = (rule, value, callback) => {
           
                // 模拟异步验证效果
                var reg=/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/;
                setTimeout(() => {
                    if (!reg.test(value)) {
                        callback(new Error('请输入正确的手机号'));
                    } else {
                         callback();
                    }
                }, 1000);
            };
            return {
                 formValidate: {
                    name: '',
                    password: '',
                    phone:'',
                    email:''
                },
                
                ruleValidate: {
                    name: [
                        { required: true, message: '姓名不能为空', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '密码不能为空', trigger: 'blur' },
                    ],
                     phone: [
                        { required: true,  validator: validatePhone,  trigger: 'blur' }
                    ],
                    email: [
                     { required: true,  validator: validateEmail,  trigger: 'blur' }
                    ]

                },
                columns: [
                    {
                        type:'selection',
                        width:60,
                        align:'center'
                    },
                    {
                        title: '姓名',
                        key: 'name',
                        render: (h, params) => {
                            return h('div', [
                                h('Icon', {
                                    props: {
                                        type: 'person'
                                    }
                                }),
                                h('strong', params.row.name)
                            ]);
                        }
                    },
                    {
                        title: '手机号',
                        key: 'phone'
                    },
                    {
                        title: '邮箱',
                        key: 'email'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 150,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.update(params.row)
                                        }
                                    }
                                }, '修改'),
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            console.log(params);
                                            this.remove(params.row._id)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                modal:false,
                filter:{
                    list:[],//装载数据
                    total:0,//总记录
                    page:1,//页码
                    limit:10,
                    name:''

                }
            }
        },
        methods: {      
            //打开 添加页面
            onOpen(){
                 this.modal = true;
              
               var obj= Object.assign(this.$data.formValidate,this.$options.data().formValidate);
                // 对象合并，并且初始表单数据
                
            },
            //更新页面的 打开
              update (row) {
                this.modal = true;
                Object.assign(this.$data.formValidate,row);
            },
             //提交添加功能
              handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                       
                        if(this.formValidate._id && this.formValidate._id.length>0){
                            if(this.formValidate.password.length<18){
                                this.formValidate.password=md5( this.formValidate.password).toString();
                            }
                            this.$http.put(`http://localhost:3000/users/data/${this.formValidate._id}`,this.formValidate)
                            .then(res=>{
                                this.$Message.success('修改成功!');
                                delete this.formValidate._id;
                                this.modal = false;
                                this.getData();
                            })
                        }else{
                         this.formValidate.password=md5( this.formValidate.password).toString();
                            this.$http.post('http://localhost:3000/users/data',this.formValidate)
                            .then(res=>{
                                this.$Message.success('添加成功!');
                                this.modal = false;
                                this.getData();
                            })
                        }
                        

                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            },
            //重置表单功能
            handleReset (name) {
                this.$refs[name].resetFields();
            },
            //删除单个功能
            remove (id) {

                this.$Modal.confirm({
                    title: '确认删除数据',
                    content: '<p>确认删除该记录吗？</p>',
                    onOk: () => {
                        
                        this.$http.delete(`http://localhost:3000/users/data/${id}`)
                        .then(res=>{
                            this.$Message.info('删除数据成功');
                            this.getData();
                        })
                       
                    },
                    onCancel: () => {
                        // this.$Message.info('点击了取消');
                    }
                });

                
            },
            //多个删除 之多选
             onSelectionChange(selection){
                if(selection && selection.length>0){
                     var ids = [];
                     let selectionLen = selection.length;
                     for(let i=0;i<selectionLen;i++){
                         ids.push(selection[i]._id);
                     }
                     this.ids = ids;
                }
            },
            //多个删除功能
             onDeletes(){
                
                 this.$Modal.confirm({
                    title: '确认删除数据',
                    content: '<p>确认删除该记录吗？</p>',
                    onOk: () => {
                   
                        this.$http.post('http://localhost:3000/users/deletes',{ids:this.ids.toString()})
                        .then(res=>{
                            this.$Message.info('删除数据成功');
                            this.getData();
                        })                    
                    },
                    onCancel: () => {
                        // this.$Message.info('点击了取消');
                    }
                });
            },
            //分页功能 获取列表数据
            getData(){
                     this.$http.post('http://localhost:3000/users/list',this.filter)
                .then(res=>{
                    this.filter.list=res.data.rows;
                    this.filter.total=res.data.total;
                    this.filter.page=res.data.page;
                })
            },
          //分页功能  改变页码
             onChange(page){
              this.filter.page = page;
              this.getData();
            },
            //分页功能  改变
            onPageSizeChange(pageSize){
                this.filter.limit = pageSize;
                this.getData();
            },
            //搜索框
            onSearch(){
                     this.getData();
            }        
        },
        //获取数据
          created () {
               this.getData();
            }
    }
</script>